When should I use CROSS APPLY over INNER JOIN?
When should I use CROSS APPLY over INNER JOIN?
357
11-Jul-2023
Updated on 12-Jul-2023
Aryan Kumar
12-Jul-2023Cross apply and inner join are both SQL join clauses that are used to combine data from two or more tables. However, they have different purposes and should be used in different situations.
Cross apply is used to create a Cartesian product of two tables. This means that it will return all possible combinations of rows from the two tables, even if there is no matching row in the other table.
Inner join is used to join two tables based on a common value. This means that it will only return rows from the two tables where there is a matching row in the other table.
In general, you should use cross apply when you want to return all possible combinations of rows from two tables. For example, you might use cross apply to get a list of all possible orders that could be made from a list of products and a list of customers.
You should use inner join when you want to return only the rows that match between two tables. For example, you might use inner join to get a list of all orders that were made by a specific customer.
Here is a table that summarizes the differences between cross apply and inner join:
Here is an example of how to use cross apply:
SQL
This code will return all possible combinations of rows from the
Customerstable and theOrderstable. This means that it will return all rows from theCustomerstable, even if there are no matching rows in theOrderstable.Here is an example of how to use inner join:
SQL
This code will return only the rows from the
Customerstable that have a matching row in theOrderstable. This means that it will only return rows from theCustomerstable where there is a corresponding order in theOrderstable.